/**
 * 波段需求
 */
import * as React from 'react'
import { Card, Button, Form, Row, Col, Select, Divider, Cascader, Icon, message, Popconfirm, Input, Modal } from 'antd'
import Authentication from '../../router/Authentication'
import { PageHeaderLayout, StandardTable, HideUpload, ModalMessage } from '../../components'
import { exportExcel, CHECK_BAND, DELETE_BAND, get, DELETE_BANDS, CHECK_BANDS } from '../../service/api'
import '../../assets/style/TableList.less'
const FormItem = Form.Item
const Option = Select.Option
const confirm = Modal.confirm;
export interface State {
  formValues: any
  pagination: any
  expandForm: boolean
  selectedRows: Array<any>
}

@Authentication
class Band extends React.Component<any, State> {
  
  state = {
    pagination: {},
    formValues: {},
    selectedRows: [],
    expandForm: false
  }
  componentDidMount () {
    //获取波段列表
    this.search(this.props.form.getFieldsValue(), {})
  }

  handleFormReset = () => {
    const { form } = this.props
    form.resetFields()
    this.setState({
      formValues: {}
    })
    //获取波段列表
    this.search(this.props.form.getFieldsValue(), {})
  }
  /**
   * 点击查询按钮
   */
  handleSearch = (e: any) => {
    e.preventDefault()
    const { form, data: { pagination } } = this.props
    form.validateFields((err: any, fieldsValue: any) => {
      if (err) return
      Object.assign(fieldsValue,{pageIndex: pagination.current})
      Object.assign(fieldsValue,{pageSize: pagination.pageSize})
      if(fieldsValue.fgid) fieldsValue.fgid = fieldsValue.fgid.join(',')
      this.setState({
        formValues: fieldsValue,
        pagination,
      })
      this.search({
        ...fieldsValue
      }, pagination)
    })
  }

  /**
   * 批量删除
   * @param param 
   * @param pageInfo 
   */
  handleDeleteBatch() {
    const { selectedRows } = this.state
    const _search = this.search
    confirm({
      title: '提示',
      content: '你确定要删除该项吗？',
      onOk() {
        get(DELETE_BANDS, { ids: selectedRows.join(',') }).then((res: any) => {
          if (res.code == '1') {
            message.success('操作成功！')
            _search({}, {})
          }else {
            message.error(res.errMsg)
          }
        })
      },
      onCancel() {},
    });
  }

  /**
   * 批量审核
   */
  handleCheckBatch() {
    const { selectedRows } = this.state
    get(CHECK_BANDS, { ids: selectedRows.join(',') }).then((res: any) => {
      if (res.code == '1') {
        message.success('操作成功！')
        this.search(this.props.form.getFieldsValue(), {})
      }else {
        message.error(res.errMsg)
      }
    })
  }

  /**
   * 调用查询方法
   */
  search (param: any , pageInfo: any) {
    const { list } = this.props
    const { pagination, formValues } = this.state
    list(param||formValues, pageInfo||pagination)
  }
  toggleForm = () => {
    const { expandForm } = this.state
    this.setState({
      expandForm: !expandForm,
    })
  }
  renderAdvancedForm() {
    const { form, categorys, minCategorys } = this.props
    const { expandForm } = this.state
    const { getFieldDecorator } = form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 34 },
        sm: { span: 12 },
        md: { span: 15 },
      },
    }
    getFieldDecorator('dlid', { initialValue: [] })
    getFieldDecorator('style', { initialValue: [] })
    const changeCateGorys = (e: string []) => {
      let dlid = e[0]
      let style = ''
      if (e.length>1) style = e[1]
      form.setFieldsValue({
        dlid,
        style
      })
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="年份" {...formItemLayout}>
              {getFieldDecorator('year',{ initialValue:2019 })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="">全部</Option>
                  <Option value="2018">2018</Option>
                  <Option value="2019">2019</Option>
                  <Option value="2020">2020</Option>
                  <Option value="2021">2021</Option>
                  <Option value="2022">2022</Option>
                  <Option value="2023">2023</Option>
                  <Option value="2024">2024</Option>
                  <Option value="2025">2025</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="风格" {...formItemLayout}>
            {getFieldDecorator('fgid')(
              <Cascader options={minCategorys} changeOnSelect placeholder="请选择风格"/>
            )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className="submitButtons" style={{textAlign: 'center'}}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>  
                {expandForm?
                  <span> 收起 <Icon type="up" /></span>:
                  <span>展开 <Icon type="down" /></span>
                }
              </a>
            </span>
          </Col>
        </Row>
        {expandForm&&(<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="分类" {...formItemLayout}>
              <Cascader options={categorys} onChange = {changeCateGorys} changeOnSelect placeholder="请选择分类"/>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="波段" {...formItemLayout}>
              {getFieldDecorator('band')(
                <Input placeholder="请输入波段"/>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态" {...formItemLayout}>
              {getFieldDecorator('status')(
                <Select placeholder="请选择状态" allowClear>
                  <Option value={1}>已审核</Option>
                  <Option value={0}>未审核</Option>
                </Select>)}
            </FormItem>
          </Col>
        </Row>)}
      </Form>
    )
  }
  /**
   * 筛选或者更改分页
   */
  handleStandardTableChange = (pagination: any, filtersArg: any, sorter: any) => {
    const { formValues } = this.state
    let params: any = formValues
    params = {
      ...params,
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
    }
    this.setState({
      formValues: params,
      pagination,
    })
    this.search(params, pagination)
  }

  //选中事件
  handleSelectRows = (rows: any []) => {
    this.setState({
      selectedRows: rows,
    })
  }

  //编辑
  handleInfo = (no: string, id: string) => {
    const { record } = this.props
    record({ id, no })
    this.props.history.push({ pathname: '/band/edit' })
  }
  handleAdd = () => {
    const { clear } = this.props
    clear()
    this.props.history.push({ pathname: '/band/edit' })
  }
  handleCheck = (id: string) => {
    get(CHECK_BAND, { id }).then((res: any) => {
      if (res.code == '1') {
        message.success('操作成功！')
        this.search(this.props.form.getFieldsValue(), {})
      }else {
        message.error(res.errMsg)
      }
    })
  }
  handleDelete = (id: string) => {
    get(DELETE_BAND, { id }).then((res: any) => {
      if (res.code == '1') {
        message.success('操作成功！')
        this.search({}, {})
      }else {
        message.error(res.errMsg)
      }
    })
  }
  render () {
    const { loading, data } = this.props
    const { selectedRows } = this.state
    const columns: any [] = [
      {
        title: '年份',
        dataIndex: 'Year',
      },
      {
        title: '波段',
        dataIndex: 'bandname',
      },
      ,{
        title: '风格',
        dataIndex: 'fgText',
        key: 'fgText',
      },
      {
        title: '大区',
        dataIndex: 'dlText'
      },
      {
        title: '品类',
        dataIndex: 'xlText'
      },
      {
        title: '上货款数',
        dataIndex: 'supplyqty'
      },
      {
        title: '提供样版数',
        dataIndex: 'kindqty'
      },
      {
        title: '上传图片截止日期',
        dataIndex: 'uploaddate'
      },
      {
        title: '上市日期',
        dataIndex: 'indate'
      },
      {
        title: '编辑人',
        dataIndex: 'editor'
      },
      {
        title: '编辑日期',
        dataIndex: 'editdate'
      },
      {
        title: '状态',
        dataIndex: 'statusText'
      },
      {
        title: '审核人',
        dataIndex: 'checker'
      },
      {
        title: '审核日期',
        dataIndex: 'checkdate',
        // sorter: true
      },
      {
        title: '审版日期',
        dataIndex: 'approvaldate',
        // sorter: true
      },
      {
        title: '邮寄样衣日期',
        dataIndex: 'maildate',
        // sorter: true
      }, {
        title: '操作',
        width: '160px',
        render: (row: any) => (
          <React.Fragment>
            <a onClick={ () => this.handleInfo(row.id, row.bandid)}>编辑</a>
            {row.status == '0'&&(<span>
              <Divider type="vertical" />
              <Popconfirm
                title="确认通过审核吗？"
                okText="确认" 
                cancelText="取消"
                onConfirm={() => this.handleCheck(row.id)}>
                <a>审核</a>
              </Popconfirm>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除该条记录吗？"
                okText="确认" 
                cancelText="取消"
                onConfirm={() => this.handleDelete(row.id)}>
                <a>删除</a>
              </Popconfirm>
            </span>)}

          </React.Fragment>
        ),
      },
    ]
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div className="tableList">
            <div className="tableListForm">{this.renderAdvancedForm()}</div>
            <div className="tableListOperator">
              <Button icon="plus" type="primary" onClick = {this.handleAdd}>
                添加
              </Button>
              <HideUpload 
                ref="MyTSingleUpdaload" 
                url="/Scm/Band/UploadImport" 
                fileType={"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"} 
                title="导入" 
                onChange={(result: any)=>{
                  if(result.code<=0){
                    ModalMessage.error(result.errMsg)
                    return
                  }
                }}
              />
              <Button icon="anticon anticon-download" type="primary" onClick = {() => exportExcel('/Scm/Band/ExportBand')}>
                导出
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button icon="delete" type="danger" onClick={() => this.handleDeleteBatch()}>删除</Button>
                  <Button icon="check" type="primary" onClick={() => this.handleCheckBatch()}>审核</Button>
                </span>
              )}
            </div>
            <StandardTable
              xscroll="2000px"
              rowKey = "id"
              select = {true}
              selectedRows = {selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    )
  }
}

export default Form.create()(Band)